package cn.wenhaha.common.utils;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 *
 * https://blog.csdn.net/u013014636/article/details/106314798
 * --------
 *
 * @author ：wyndem
 * @Date ：Created in 2022-07-07 22:44
 */
@Component
public class SpringAddWebApi {
    private String file="D:\\code\\java\\git\\salesforcesDataSync\\test-1.0-SNAPSHOT.jar";
    @Resource
    private ApplicationContext applicationContext;

    public  void invoke(){
        try {
            String className="org.example.TestController";
            registerBean(className);
            registerController(StringUtils.uncapitalize(className.substring(className.lastIndexOf(".") + 1)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public  void registerBean(String clazzName) throws Exception{
        URL url = new File(file).toURI().toURL();

//        URLClassLoader loader = (URLClassLoader) ApplicationBootstrap.class.getClassLoader();
//        Method add = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
//        add.setAccessible(true);
//        add.invoke(loader, url);

        URLClassLoader loader = new URLClassLoader(new URL[]{url});
//        String clazzName = "test1.controller.MyTestController1";
        Class<?> clazz = loader.loadClass(clazzName);


//        applicationContext.getClassLoader().loadClass("test.MyController");
//        DefaultListableBeanFactory factory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();

        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
        BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();

        //设置当前bean定义对象是单利的
        beanDefinition.setScope("singleton");

        //将变量首字母置小写
        String beanName = StringUtils.uncapitalize(clazzName);

        beanName =  beanName.substring(beanName.lastIndexOf(".")+1);
        beanName = StringUtils.uncapitalize(beanName);

        //将applicationContext转换为ConfigurableApplicationContext
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;

        // 获取bean工厂并转换为DefaultListableBeanFactory
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
        defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinition);
    }

    /**
     * 注册Controller
     * @param controllerBeanName
     * @throws Exception
     */
    public  void registerController(String controllerBeanName) throws Exception{
        final RequestMappingHandlerMapping requestMappingHandlerMapping=
                applicationContext.getBean(RequestMappingHandlerMapping.class);
        if(requestMappingHandlerMapping!=null){
            String handler=controllerBeanName;
            Object controller= applicationContext.getBean(handler);
            if(controller==null){
                return;
            }
//            unregisterController(controllerBeanName);
            //注册Controller
            Method method=requestMappingHandlerMapping.getClass().getSuperclass().getSuperclass().
                    getDeclaredMethod("detectHandlerMethods",Object.class);
            //将private改为可使用
            method.setAccessible(true);
            method.invoke(requestMappingHandlerMapping,handler);
        }
    }


    /**
     * 去掉Controller的Mapping
     * @param controllerBeanName
     */
    public  void unregisterController(String controllerBeanName){
        final RequestMappingHandlerMapping requestMappingHandlerMapping=(RequestMappingHandlerMapping)
                applicationContext.getBean("requestMappingHandlerMapping");
        if(requestMappingHandlerMapping!=null){
            String handler=controllerBeanName;
            Object controller= applicationContext.getBean(handler);
            if(controller==null){
                return;
            }
            final Class<?> targetClass=controller.getClass();
            ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
                public void doWith(Method method) {
                    Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
                    try {
                        Method createMappingMethod = RequestMappingHandlerMapping.class.
                                getDeclaredMethod("getMappingForMethod", Method.class, Class.class);
                        createMappingMethod.setAccessible(true);
                        RequestMappingInfo requestMappingInfo =(RequestMappingInfo)
                                createMappingMethod.invoke(requestMappingHandlerMapping,specificMethod,targetClass);
                        if(requestMappingInfo != null) {
                            requestMappingHandlerMapping.unregisterMapping(requestMappingInfo);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }, ReflectionUtils.USER_DECLARED_METHODS);
        }
    }


}
